<template>
  <div>
    <a-card :bordered="false" hoverable :bodyStyle="{ height: '100%' }" :style="{ height: '100%' }">
      <a-card-grid style="width:25%;textAlign:'center';height:100%">
        <div style="height:100%">
          <div>
            <happy-scroll color="rgba(0,0,0,0.5)" size="5" :min-length-h="400" resize>
              <div style="min-height:400px">
                <a-tree
                  showLine
                  checkable
                  defaultExpandAll
                  @expand="onExpand"
                  :expandedKeys="expandedKeys"
                  :selectedKeys="selectedKeys"
                  :autoExpandParent="autoExpandParent"
                  :treeData="routerList"
                  v-model="functionCheckedKeys"
                >
                  <template slot="title" slot-scope="{title}">
                    <span v-if="title.indexOf(searchValue) > -1">
                      {{ title.substr(0, title.indexOf(searchValue)) }}
                      <span class="search-tree-color">{{ searchValue }}</span>
                      {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
                    </span>
                    <span v-else>{{ title }}</span>
                  </template>
                </a-tree>
              </div>
            </happy-scroll>
          </div>
        </div>
      </a-card-grid>
      <a-card-grid style="width:75%;textAlign:'center';height:100%">
        <div style="min-height:425px">
          <div class="table-page-search-wrapper">
            <a-form layout="horizontal" >
              <a-row :gutter="8">
                <a-col :md="8" :sm="24">
                  <a-form-item label="查询类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-select v-model="queryUserParam.searchType" placeholder="默认查询从未授权用户" @change="searchTypeChange">
                      <a-select-option value="1">从未授权用户</a-select-option>
                      <a-select-option value="2">已授权用户</a-select-option>
                      <a-select-option value="3">全部</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item label="姓名" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-input v-model="queryUserParam.fullName" placeholder="支持模糊查询"/>
                  </a-form-item>
                </a-col>
                <template v-if="advanced">
                  <a-col :md="8" :sm="24">
                    <a-form-item label="用户名" :labelCol="labelCol" :wrapperCol="wrapperCol">
                      <a-input v-model="queryUserParam.userName" placeholder="支持模糊查询"/>
                    </a-form-item>
                  </a-col>
                  <a-col :md="8" :sm="24">
                    <a-form-item label="所属组织" :labelCol="labelCol" :wrapperCol="wrapperCol">
                      <a-tree-select
                        showSearch
                        v-model="queryUserParam.orgIds"
                        style="width: 100%"
                        :value="orgSelectTreeValue"
                        :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                        placeholder="支持多选"
                        treeNodeFilterProp="title"
                        allowClear
                        multiple
                        treeDefaultExpandAll
                        :treeData="orgSelectTreeData"
                        @change="onChangeOrgSelectTree"
                        @search="onSearchOrgSelectTree"
                        @select="onSelectOrgSelectTree"
                      >
                      </a-tree-select>
                    </a-form-item>
                  </a-col>
                  <a-col :md="8" :sm="24">
                    <a-form-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
                      <a-select v-model="queryUserParam.status" placeholder="请选择" allowClear>
                        <a-select-option value="0">禁用</a-select-option>
                        <a-select-option value="1">启用</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :md="8" :sm="24">
                    <a-form-item label="用户类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
                      <a-select v-model="queryUserParam.userTypes" mode="multiple" placeholder="支持多选" allowClear >
                        <a-select-option v-for="item in dictData.userType" :key="item.dictKey" :value="item.dictKey">{{ item.dictValue }}</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                </template>
                <a-col :md="!advanced && 8 || 24" :sm="24">
                  <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                    <a-button type="primary" @click="() =>{this.findUserListBtn()}">查询</a-button>
                    <a-button style="margin-left: 8px" @click="() => {this.clearAll()}">重置</a-button>
                    <a @click="toggleAdvanced" style="margin-left: 8px">
                      {{ advanced ? '收起' : '展开' }}
                      <a-icon :type="advanced ? 'up' : 'down'"/>
                    </a>
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <vxe-grid
            class="vxe-table-antd"
            resizable
            show-overflow
            ref="userListTable"
            stripe
            border
            highlight-hover-row
            highlight-current-row
            highlight-hover-column
            highlight-current-column
            highlight-cell
            height="350"
            size="small"
            row-id="userId"
            :columns="userColumn"
            :data="userTableData"
            :loading="userLoading"
            :start-index="(userTablePage.currentPage - 1) * userTablePage.pageSize"
            :pager-config="userTablePage"
            @page-change="handleUserPageChange"
            :checkbox-config="{reserve: true}"
            @select-change="userSelectChange"
            @select-all="selectUserAllEvent"
          >
          </vxe-grid>
        </div>
      </a-card-grid>
    </a-card>
  </div>
</template>

<script>
import { getRouterNoPrivilegeUserList, getRouterFunctionTree,getOrgSelectTree,getBatchDict } from "@/services/system/api"
import modal from 'ant-design-vue/es/modal'
const statusMap = {
  0: {
    status: 'error',
    text: '禁用'
  },
  1: {
    status: 'processing',
    text: '启用'
  }
}
const flagMap = {
  0: {
    status: 'default',
    text: '否'
  },
  1: {
    status: 'success',
    text: '是'
  }
}
export default {
  name: 'RouterUserManager',
  components: {
  },
  props: {
    routerInfo: {
      type: Object,
      default: () => {},
      required: false
    }
  },
  data () {
    return {
      description: '路由授权用户界面',
      // 高级搜索 展开/关闭
      advanced: false,
      dictData: {},
      orgSelectTreeValue: undefined,
      orgSelectTreeData: [],
      functionCheckedKeys: [],
      userChecked: [],
      // 用户查询条件
      queryUserParam: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 }
      },
      // 路由id
      routerId: null,
      // 路由功能树
      expandedKeys: [],
      selectedKeys: [],
      searchValue: '',
      autoExpandParent: true,
      routerList: [],
      // 用户列表参数
      userTableData: [],
      userLoading: false,
      userTablePage: {
        total: 0,
        pageNum: 1,
        currentPage: 1,
        pageSize: 20
      },
      userColumn: [
        { type: 'checkbox', width: 50, fixed: 'left' },
        { type: 'seq', width: 50, fixed: 'left', align: 'center', title: '序号' },
        { field: 'userId', title: '用户Id',visible: false, fixed: 'left', align: 'center', width: 150 },
        { field: 'userName', title: '用户名', fixed: 'left', align: 'center', width: 150 },
        { field: 'fullName', title: '姓名', align: 'center', width: 150 },
        { field: 'userType', title: '用户类型key', visible: false,align: 'center', width: 150 },
        { field: 'userTypeName', title: '用户类型', align: 'center', width: 150 },
        { field: 'status', title: '状态', align: 'center', width: 80, slots: { default: ({ row }) => { return [this.formatStatus(row.status)] } } },
        { field: 'email', title: '电子邮箱', align: 'center', showOverflow: true, width: 150 },
        { field: 'cellphone', title: '手机', align: 'center', width: 100 },
        { field: 'idcard', title: '身份证', align: 'center', width: 150 },
        { field: 'address', title: '地址', align: 'center', showOverflow: true, width: 200 },
        { field: 'officePhone', title: '办公室电话', align: 'center', width: 100 },
        { field: 'shortPhone', title: '短号', align: 'center', width: 60 },
        { field: 'orgId', title: '所属组织', align: 'center', showOverflow: true, width: 150 },
        { field: 'orgName', title: '所属组织', align: 'center', showOverflow: true, width: 150 },
        { field: 'superiorsName', title: '直接上级', align: 'center', width: 150 },
        { field: 'regdate', title: '创建日期', align: 'center', width: 80 },
        { field: 'remarks', title: '备注', align: 'center', showOverflow: true, width: 250 }
      ]
    }
  },
  created () {
    if (this.routerInfo) {
      this.routerId = this.routerInfo.routerId
    } else {
      this.routerId = null
    }
    const params = {}
    params.dictFields = 'userType'
    this.$http.post(getBatchDict,params).then(res => {
      this.dictData = res.result
    })
    // 下拉组织树初始化
    this.$http.post(getOrgSelectTree,params).then(res => {
      this.orgSelectTreeData = res.result
    })
    // 初始化数据
    this.findRouterFunctionTree()
    const queryParam = {}
    queryParam.searchType = '1'
    this.queryUserParam = queryParam
    this.findUserList()
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    }
  },
  methods: {
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    onChangeOrgSelectTree (value) {
      console.log(value)
      this.orgSelectTreeValue = value
    },
    onSearchOrgSelectTree () {
      console.log(...arguments)
    },
    onSelectOrgSelectTree () {
      console.log(...arguments)
    },
    findRouterFunctionTree () {
      if (this.routerId) {
        // 获取节点相关信息
        const params = {}
        params.routerId = this.routerId
        setTimeout(() => {
          this.$http.post(getRouterFunctionTree,params).then((res) => {
            this.routerList = res.result.routerList
            this.expandedKeys = res.result.expandedKeys
          }).catch(() => {
          })
        }, 50)
      }
    },
    findUserListBtn () {
      if (this.routerId) {
        this.userTablePage.pageNum = 1
        this.userTablePage.currentPage = 1
      } else {
        modal.warn({ title: '系统异常提示', content: '没有传入路由id' })
      }
    },
    findUserList () {
      if (this.routerId) {
        this.userloading = true
        const params = Object.assign(this.queryUserParam, this.userTablePage)
        params.routerId = this.routerId
        this.$http.post(getRouterNoPrivilegeUserList,params).then((res) => {
          this.userTableData = res.result.list
          this.userTablePage.total = res.result.total
          this.userTablePage.pageNum = res.result.pageNum
          this.userTablePage.currentPage = res.result.pageNum
          this.userTablePage.pageSize = res.result.pageSize
          this.userLoading = false
        }).catch(() => {
          this.userLoading = false
        })
      } else {
        modal.warn({ title: '系统异常提示', content: '没有传入路由id' })
      }
    },
    onExpand (expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    formatStatus (cellValue) {
      if (cellValue) {
        const text = statusMap[cellValue].text
        const status = statusMap[cellValue].status
        if (text) {
          return <a-badge status={status} text={text}/>
        } else {
          return cellValue
        }
      }
    },
    formatflag (cellValue) {
      if (cellValue) {
        const text = flagMap[cellValue].text
        const status = flagMap[cellValue].status
        if (text) {
          return <a-badge status={status} text={text}/>
        } else {
          return cellValue
        }
      }
    },
    handleUserPageChange ({ currentPage, pageSize }) {
      this.userTablePage.pageNum = currentPage
      this.userTablePage.currentPage = currentPage
      this.userTablePage.pageSize = pageSize
      this.findUserList()
    },
    userSelectChange () {
      let data = []
      const thisChecked = this.$refs.userListTable.getCheckboxRecords()
      if (thisChecked && thisChecked.length > 0) {
        data = thisChecked
      }
      const selectReserveRecords = this.$refs.userListTable.getCheckboxReserveRecords()
      if (selectReserveRecords && selectReserveRecords.length > 0) {
        selectReserveRecords.forEach((item) => {
          data.push(item)
        })
      }
      this.userChecked = data
    },
    selectUserAllEvent ({ checked }) {
      console.log(checked ? '所有勾选事件' : '所有取消事件')
      let data = []
      const thisChecked = this.$refs.userListTable.getCheckboxRecords()
      if (thisChecked && thisChecked.length > 0) {
        data = thisChecked
      }
      const selectReserveRecords = this.$refs.userListTable.getCheckboxReserveRecords()
      if (selectReserveRecords && selectReserveRecords.length > 0) {
        selectReserveRecords.forEach((item) => {
          data.push(item)
        })
      }
      this.userChecked = data
    },
    searchTypeChange () {
      this.findUserList()
    },
    clearAll () {
      this.queryUserParam = {}
      this.findUserList()
      setTimeout(() => {
        this.userChecked = []
        this.$refs.userListTable.clearSelection()
        this.$refs.userListTable.clearSelectReserve()
      }, 50)
    }
  }
}
</script>
<style lang="less" scoped>
@import "~ant-design-vue/lib/style/themes/default.less";
.search-tree-color {
  color : @primary-color
}
</style>
